import random
from time import sleep
import json
import logging
_LOGGER = logging.getLogger(__name__)
from homeassistant.helpers.json import JSONEncoder
from abc import abstractmethod
from .const import(
    sub_topic,
    sub_topic_ha,
    pub_topic,
    CONF_BROKER,
    CONF_BROKER_PORT
)

class MqttClient(object):
    def __init__(self,hass,username,password) -> None:
        self.broker = CONF_BROKER
        self.port = CONF_BROKER_PORT
        self.username = username
        self.password = password
        self.topic = sub_topic + username + "/#"
        self.topic_ha = sub_topic_ha + username + "/#"
        self.client_id = f'python-mqtt-{random.randint(0, 1000)}'
        self.client = None
        self._hass = hass
        self._event = None
        self.flag = False

    def on_connect(self,client, userdata, flags, rc):
        self.client.subscribe(self.topic)
        self.client.subscribe(self.topic_ha)
        self.client.on_message = self.on_message
        if rc == 0:
            _LOGGER.info("云平台连接成功")
            self._hass.states.set("multi_platform_voice.state", "success")
            self.flag = True
        else:
            _LOGGER.error('云平台连接失败')
            self._hass.states.set("multi_platform_voice.state", "error")
        

    def connect_mqtt(self):
        from paho.mqtt import client as mqtt_client
        self.client = mqtt_client.Client(self.client_id)
        self.client.username_pw_set(self.username,self.password)
        self.client.on_connect = self.on_connect
        try:
            self.client.connect(self.broker, self.port,30)
        except ConnectionRefusedError as e :
            _LOGGER.error(e)
            self._hass.states.set("multi_platform_voice.state", "error")
            sleep(3)
            self.connect_mqtt() 
    def json_loads(self,msg):
        return json.loads(json.dumps(msg, sort_keys=True, cls=JSONEncoder).encode('UTF-8'))


    def publish(self,msg):
        s = json.dumps(msg, sort_keys=True, cls=JSONEncoder).encode('UTF-8')
        self.client.publish(pub_topic + self.username, s)

    @abstractmethod
    def on_message(self,client, userdata, msg):
        pass

 